package com.legendshop.security.handler;

import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;

import com.legendshop.oa.constants.EventOperationTypeEnum;
import com.legendshop.oa.constants.EventTypeEnum;
import com.legendshop.oa.security.UserDetail;
import com.legendshop.oa.service.EventService;
import com.legendshop.util.AppUtils;
import com.legendshop.util.DateUtil;

public class AuthenticationSuccessBusinessHandlerImpl implements AuthenticationSuccessBusinessHandler {
	
	/** The log. */
	private final Logger logger = LoggerFactory.getLogger(AuthenticationSuccessBusinessHandlerImpl.class);
	
	private EventService eventService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
		// 如果是采用HTTPS登录，其他链接采用HTTP， 则要将HTTP的cookies设置
		if (request.isSecure()) {
			Cookie cookie = new Cookie("JSESSIONID", request.getSession().getId());
			cookie.setMaxAge(-1);// no store
			cookie.setSecure(false);
			String contextPath = request.getContextPath();
			if (AppUtils.isBlank(contextPath)) {
				contextPath = "/";
			}
			cookie.setPath(contextPath);
			response.addCookie(cookie);
		}

		this.loginSuccessProcess(request, response, authentication);
	}

	/**
	 * 登录成功后的处理
	 * 记录登录历史
	 * @param request
	 * @param response
	 * @param authentication
	 */
	public void loginSuccessProcess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
		UserDetail ud = (UserDetail)authentication.getPrincipal();
		logger.info(ud.getUsername() + "登录成功");
		String date = DateUtil.DateToString(new Date(), DateUtil.CM_LONG_DATE_FORMAT);
		eventService.saveEvent(ud, ud.getUserId(),  " 用户  " + ud.getUsername() + "(" + ud.getRealName() + ") 于" + request.getRemoteAddr() + ", 时间" + date + "登录", EventTypeEnum.LOGIN, EventOperationTypeEnum.LOGIN);
	}

	public void setEventService(EventService eventService) {
		this.eventService = eventService;
	}

}
